var config = require("gfportal").config,
    services = require("gfportal").services,
    controllers = require("gfportal").controllers,
    logger = services.logger,
    logging_middleware = services.logging_middleware,
    log_admin_op = require("gfportal").controllers.log_admin_op,
    log_admin_op = require("gfportal").controllers.log_admin_op,
    flash = require('connect-flash'),
    express = require('express'),
    MongoStore = require('connect-mongo')(express),
    http = require('http'),
    path = require('path'),
    set_http_server = require("gfportal").lib.set_http_server,
    set_server_port = require("gfportal").lib.set_server_port,
    util = require("util"),
    cache_json = controllers.cache_json,
    gfrouter = require("gfportal").lib.gfrouter,
    track_source = controllers.track_source,
    prevent_sql_inject = controllers.prevent_sql_inject,
    noCache = controllers.noCache;
// RedisStore = require('connect-redis')(express);;

var app = express();
var session_config;
var g_default_port = 4000;
//默认使用mongodb进行session的缓存，设置为false可以使用redis进行缓存
var mongo_cache = true;
if (mongo_cache) {
    store = new MongoStore({
        db: config.sessiondb
    });
} else {
    store = new RedisStore(config.redisdb);
}


if (process.env.NODE_ENV == "development") {
    session_config = {
        key: 'gfportaltestsid',
        secret: 'agile2013',
        store: store
    };
} else if (process.env.NODE_ENV == "uat") {
    g_default_port = 3001;
    session_config = {
        cookie: {
            domain: ".gf.com.cn"
        },
        key: 'gfportaluatsid',
        secret: 'agile2013',
        store: store
    };
} else {
    session_config = {
        cookie: {
            domain: ".gf.com.cn"
        },
        key: 'gfportalsid',
        secret: 'agile2013',
        store: store
    };
};


app.configure(function() {
    app.set('port', process.env.PORT || g_default_port);

    // General middleware
    app.use(express.favicon());
    app.use(express.logger("PV`:date`:method`:url`:response-time`:res[Content-Length]"));
    app.use(express.cookieParser());
    app.use(express.bodyParser());
    app.use(express.methodOverride());
    // app.use(prevent_sql_inject);
    app.use(gfrouter("non_session"));
    app.use(express.session(session_config));
    app.use(flash());
    app.use(logging_middleware);
    // app.use(log_admin_op);
    // app.use(track_source);
    // app.use(noCache);
    if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
        app.use(services.field_picker_middleware);
    }
    app.use(app.router);
    app.use(express.static(path.join(__dirname, 'public')));
    if (!process.env.NODE_ENV || process.env.NODE_ENV === 'development') {
        app.use('/dev', express.static(path.join(__dirname, 'dev')));
    }
    app.use(function(err, req, res, next) {
        var error_msg;
        var user = '';
        if (req && req.session && req.session.user) {
            if (req.session.user.trade)
                user = req.session.user.trade.khbh;
            else if (req.session.user.portal)
                user = req.session.user.portal.service_name;
            else
                user = "";
        }
        error_msg = util.inspect({
            type: "Exception",
            path: req.path,
            method: req.method,
            query: req.query,
            body: req.body,
            user: user,
            error: err.message || err.toString(),
            stack: err.stack
        });
        logger.error(error_msg);
        console.error(error_msg);
        res.send(500, {
            error: err.message || err.toString()
        });
    });
});

var initApp = function() {
    require("./urls")(app);
    app.enable('trust proxy'); //IMPORTANT! behind nginx, this is required!

    var server = http.createServer(app);
    set_http_server(server);
    set_server_port(app.get('port'));
    server.listen(app.get('port'), function() {
        console.log("Express server listening on port " + app.get('port'));
    });
};

var d = require('domain').create();
d.on('error', function(err) {
    var error_msg = util.inspect({
        type: "Process exception",
        error: err
    });
    console.error(error_msg);
});
d.run(function() {
    initApp();
});
